package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.common.AppThreadLocalUtil;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ArticleSearchServiceImpl implements ArticleSearchService {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ApUserSearchService userSearchService;

    /**
     * 根据条件分页搜索
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        //1. 校验并修正参数
        if(null == dto){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //异步保存搜索的关键字
        if(StringUtils.isNotEmpty(dto.getSearchWords()) && dto.getFromIndex() == 0){
            userSearchService.insert(dto.getSearchWords(), AppThreadLocalUtil.getUser().getId());
        }

        //3. 根据idea的提示创建请求对象
        SearchRequest searchRequest = new SearchRequest("app_info_article");
        //4. 设置搜索的条件
        BoolQueryBuilder booleanQuery = QueryBuilders.boolQuery();
        if(StringUtils.isEmpty(dto.getSearchWords())){
            booleanQuery.must(QueryBuilders.matchAllQuery());
        }else{
            //多字段查询
            booleanQuery.must(QueryBuilders.queryStringQuery(dto.getSearchWords()).field("title").field("content").defaultOperator(Operator.OR));
        }

        //时间过滤
        booleanQuery.filter(QueryBuilders.rangeQuery("publishTime").lte(dto.getMinBehotTime()));
        searchRequest.source().query(booleanQuery);

        //5. 设置分页参数
        searchRequest.source().from(dto.getFromIndex()).size(dto.getPageSize());

        //6. 设置排序规则
        searchRequest.source().sort("publishTime", SortOrder.DESC);

        //7. 设置高亮显示
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<font style='color: red; font-size: inherit;'>");
        highlightBuilder.postTags("</font>");
        searchRequest.source().highlighter(highlightBuilder);

        //2. 通过核心对象调用搜索方法
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        //8. 解析结果并返回
        SearchHits searchHits = response.getHits();
        //查询到的总记录数
        long total = searchHits.getTotalHits().value;
        System.out.println("查询到的总记录数 : " + total);
        //获取到我们命中的对象
        SearchHit[] hits = searchHits.getHits();
        List<Map> result = new ArrayList<>(hits.length);

        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            Map map = JSON.parseObject(json, Map.class);
            //解析高亮数据
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if(null != highlightFields && highlightFields.size() > 0){
                HighlightField highlightField = highlightFields.get("title");
                if(null != highlightField){
                    String _name = highlightField.getFragments()[0].toString();
                    map.put("h_title", _name);
                }
            }else{
                //前端使用的字段是h_title
                map.put("h_title", map.get("title"));
            }

            result.add(map);
        }

        return ResponseResult.okResult(result);
    }
}
